<template>
  <el-dialog title="分配角色" :visible="roleShow" @close="close">
    <!-- 多选框 -->
    <el-checkbox-group v-model="roleIds">
      <!-- 注意label才是存储的值 -->
      <el-checkbox v-for="item of list" :key="item.id" :label="item.id" >
        {{ item.name }}
      </el-checkbox>
    </el-checkbox-group>
    <!-- 按钮区 -->
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" type="primary" @click="btn">确定</el-button>
        <el-button size="small" @click="close">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { getRoleList } from "@/api/setting";
import { getUserDetailById } from '@/api/user'
import { assignRoles } from "@/api/employees";
export default {
  name: 'assignRole',
  props: {
    roleShow: {
      type: Boolean,
      default: false,
    },
    userId: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      list: [], // 存储可选择的所有的角色
      roleIds: [] // 存储用户当前的角色
    }
  },
  created () {
    this.getRoleList() 
  },
  methods: {
    async getRoleList() {
      // 为什么只要获取20条 因为角色过多就会就没有必要做角色
      const { rows } = await getRoleList({ page: 1, pagesize: 20 })
      this.list = rows
    },
    // 这里为什么不用userId 因为props 传过来的数据是异步 用userid可能获取不到值
    async getUserDetailById(id) {
      const { roleIds } = await getUserDetailById(id)
      this.roleIds = roleIds
    },
    async btn() {
      await assignRoles({id:this.userId,roleIds:this.roleIds})
      this.$emit('update:roleShow', false)
      this.$message.success('分配成功')
    },
    close() {
      this.roleIds = [] // 把id数组赋值为空
      this.$emit('update:roleShow', false)
    }
  }
}
</script>

<style>

</style>